<?php

declare(strict_types=1);

namespace app\shop\controller\admin\activity;

use think\Request;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\shop\model\activity\Activity as ActivityModel;
use app\shop\model\goods\Goods as GoodsModel;
use app\shop\library\activity\Activity as ActivityManager;
use app\shop\library\activity\traits\CheckActivity;
use app\shop\model\goods\Sku;
use app\shop\model\goods\SkuPrice;

/**
 * 活动
 */
class Activity extends Backend
{
    use CheckActivity;

    protected $manager = null;

    public function initialize()
    {
        $this->model = new ActivityModel;
        $this->manager = app('activity');
    }


    /**
     * 活动列表
     *
     * @return \think\Response
     */
    public function list($type)
    {
        $activities = $this->model->sheepFilter()->where('type', $type)->paginate(request()->param('list_rows', 10))->toArray();

        $items = $activities['data'];

        // 关联活动的商品
        $goodsIds = array_values(array_filter(array_column($items, 'goods_ids')));
        $goodsIdsArr = [];
        foreach ($goodsIds as $ids) {
            $idsArr = explode(',', $ids);
            $goodsIdsArr = array_merge($goodsIdsArr, $idsArr);
        }
        $goodsIdsArr = array_values(array_filter(array_unique($goodsIdsArr)));
        if ($goodsIdsArr) {
            // 查询商品
            $goods = GoodsModel::where('id', 'in', $goodsIdsArr)->select();
            $goods = $goods->column(null, 'id');
        }
        foreach ($items as $key => $activity) {
            $items[$key]['goods'] = [];
            if ($activity['goods_ids']) {
                $idsArr = explode(',', $activity['goods_ids']);
                foreach ($idsArr as $id) {
                    if (isset($goods[$id])) {
                        $items[$key]['goods'][] = $goods[$id];
                    }
                }
            }
        }

        $activities['data'] = $items;

        return success('获取成功', $activities);
    }




    // 获取活动类型
    public function getType()
    {
        $typeList = $this->model->typeList();

        $result = [
            'type_list' => $typeList,
        ];

        $data = [];
        foreach ($result as $key => $list) {
            $data[$key][] = ['name' => '全部', 'type' => 'all'];

            foreach ($list as $k => $v) {
                $data[$key][] = [
                    'name' => $v,
                    'type' => $k
                ];
            }
        }

        return success('获取成功', $data);
    }


    /**
     * 添加活动
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $params = $this->request->only([
            'title', 'goods_ids', 'type', 'prehead_time', 'start_time', 'end_time',
            'rules', 'richtext_id', 'richtext_title', 'goods_list'
        ]);
        $this->svalidate($params, ".add");

        Db::transaction(function () use ($params) {
            $this->manager->save($params);
        });
        return success('保存成功');
    }



    /**
     * 活动详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $activity = $this->model->findOrFail($id);
        // 活动附加数据
        $activity->goods_list = $activity->goods_list;
        $activity->rules = $activity->rules;

        return success('获取成功', $activity);
    }


    /**
     * 修改活动
     *
     * @return \think\Response
     */
    public function edit($id)
    {
        $params = $this->request->only([
            'title', 'goods_ids', 'prehead_time', 'start_time', 'end_time',
            'rules', 'richtext_id', 'richtext_title', 'goods_list'
        ]);
        $this->svalidate($params);

        $id = explode(',', $id);
        Db::transaction(function () use ($id, $params) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $activity) {
                $this->manager->update($activity, $params);
            }
        });
        return success('更新成功');
    }


    /**
     * 获取活动商品规格并且初始化
     *
     * @param Request $request
     * @return \think\Response
     */
    public function skus(Request $request)
    {
        $params = $request->param();
        $id = $params['id'] ?? 0;
        $goods_id = $params['goods_id'] ?? 0;
        $activity_type = $params['activity_type'] ?? '';
        $start_time = $params['start_time'] ?? '';
        $end_time = $params['end_time'] ?? '';
        $prehead_time = $params['prehead_time'] ?? '';

        if ($start_time && $end_time && $activity_type) {
            // 如果存在开始结束时间，并且是要修改
            $goodsList = [$goods_id => ['id' => $goods_id]];

            $this->checkActivityConflict([
                'type' => $activity_type,
                'classify' => $this->model->getClassify($activity_type),
                'start_time' => $start_time,
                'end_time' => $end_time,
                'prehead_time' => $prehead_time
            ], $goodsList, $id);
        }

        // 商品规格
        $skus = Sku::with('children')->where('goods_id', $goods_id)->where('parent_id', 0)->select();

        // 获取规格
        $skuPrices = SkuPrice::with(['activity_sku_price' => function ($query) use ($id) {
            $query->where('activity_id', $id);
        }])->where('goods_id', $goods_id)->select();


        //编辑
        $activitySkuPrices = [];
        foreach ($skuPrices as $k => $skuPrice) {
            $activitySkuPrices[$k] = $skuPrice->activity_sku_price ? $skuPrice->activity_sku_price->toArray() : [];
            // 活动规格数据初始化
            if (!$activitySkuPrices[$k]) {
                $activitySkuPrices[$k]['id'] = 0;
                $activitySkuPrices[$k]['status'] = 'down';
                $activitySkuPrices[$k]['price'] = '';
                $activitySkuPrices[$k]['stock'] = '';
                $activitySkuPrices[$k]['sales'] = '0';
                $activitySkuPrices[$k]['goods_sku_price_id'] = $skuPrice->id;
            }

            // 个性化初始化每个活动的 规格 字段
            $activitySkuPrices[$k] = app('activity')->showSkuPrice($activity_type, $activitySkuPrices[$k]);
        }

        return success('获取成功', [
            'skus' => $skus,
            'sku_prices' => $skuPrices,
            'activity_sku_prices' => $activitySkuPrices,
        ]);
    }


    /**
     * 删除活动
     *
     * @param string $id 要删除的活动列表
     * @return void
     */
    public function delete($id)
    {
        $id = explode(',', $id);

        Db::transaction(function () use ($id) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $activity) {
                $this->manager->delete($activity);
            }
        });

        return success('删除成功');
    }



    public function select($type) 
    {
        $activities = $this->model->sheepFilter()->whereIn('type', $type)->paginate(request()->param('list_rows', 10))->toArray();

        return success('获取成功', $activities);
    }


    /**
     * 回收站
     *
     * @return void
     */
    public function recyclebin($type)
    {
        $activities = $this->model->onlyTrashed()->sheepFilter()
            ->where('type', $type)
            ->paginate(request()->param('list_rows', 10));

        return success('获取成功', $activities);
    }

}
